//
//  ViewController.m
//  PhotoSelector
//  http://blog.csdn.net/lihuiqwertyuiop/article/details/40015521
//  Created by dayu on 15/5/15.
//  Copyright (c) 2015年 dayu. All rights reserved.
//

#import "ViewController.h"
#import "TTPhotoMaskView.h"

@interface ViewController ()<TTPhotoMaskViewDelegate, UIScrollViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, weak) IBOutlet TTPhotoMaskView *maskView;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIScrollView *scrollView;
@property (nonatomic, strong) UIImage *originImage;
@property (nonatomic, assign) CGRect pickingFieldRect;
@property (nonatomic, assign) BOOL needAdjustScrollViewZoomScale;
@end

@implementation ViewController

- (UIImage *)originImage {
    if (!_originImage) {
        _originImage = [UIImage imageNamed:@"girl.jpg"];
    }
    return _originImage;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.maskView.delegate = self;
    self.scrollView.delegate = self;

//    self.scrollView.maximumZoomScale = 2;
//    self.scrollView.minimumZoomScale = 0.5;
    self.scrollView.backgroundColor = [UIColor redColor];

}

- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id)coordinator
{
    [super willTransitionToTraitCollection:newCollection withTransitionCoordinator:coordinator];
    [self.maskView setNeedsDisplay];
}

- (void)pickingFieldRectChangedTo:(CGRect)rect
{
    self.pickingFieldRect = rect;
    CGFloat topGap = rect.origin.y;
    CGFloat leftGap = rect.origin.x;
//    self.scrollView.scrollIndicatorInsets = UIEdgeInsetsMake(topGap, leftGap, topGap, leftGap);
//    step 1: setup contentInset
    self.scrollView.contentInset = UIEdgeInsetsMake(topGap, leftGap, topGap, leftGap);
    
    CGFloat maskCircleWidth = rect.size.width;
    CGSize imageSize = self.originImage.size;
    //setp 2: setup contentSize:
    self.scrollView.contentSize = imageSize;
    CGFloat minimunZoomScale = imageSize.width < imageSize.height ? maskCircleWidth / imageSize.width : maskCircleWidth / imageSize.height;
    CGFloat maximumZoomScale = 5;
    //step 3: setup minimum and maximum zoomScale
    self.scrollView.minimumZoomScale = minimunZoomScale;
    self.scrollView.maximumZoomScale = maximumZoomScale;
    self.scrollView.zoomScale = self.scrollView.zoomScale < minimunZoomScale ? minimunZoomScale : self.scrollView.zoomScale;
    
    //step 4: setup current zoom scale if needed:
    if (self.needAdjustScrollViewZoomScale) {
        CGFloat temp = self.view.bounds.size.width < self.view.bounds.size.height ? self.view.bounds.size.width : self.view.bounds.size.height;
        minimunZoomScale = imageSize.width < imageSize.height ? temp / imageSize.width : temp / imageSize.height;
        self.scrollView.zoomScale = minimunZoomScale;
        self.needAdjustScrollViewZoomScale = NO;
    }
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view {
//    CGRect frame = self.imageView.frame;
//    frame.size.width *= scrollView.zoomScale;
//    frame.size.height *= scrollView.zoomScale;
//    self.imageView.frame = frame;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return self.imageView;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
//    if (touch.view == self.imageView) {
//        
//        self.imageView.frame = (CGRect){[touch locationInView:self.view], self.imageView.frame.size};
//    }
}

- (IBAction)makeSure {
    
    UIImage *image = [self screenshotOnCurrentView];
    //保存图片到相册
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);
}

//屏幕截图
- (UIImage *)screenshotOnCurrentView {
    
    //创建图像上下文
    CGSize size = self.maskView.frame.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
//    UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.maskView.frame];
//    
//    UIBezierPath *pickingFieldPath = [UIBezierPath bezierPathWithOvalInRect:self.pickingFieldRect];
////    [pickingFieldPath fill];
//    CGContextAddRect(ctx, self.maskView.frame);
//    CGContextAddArcToPoint(ctx, <#CGFloat x1#>, <#CGFloat y1#>, <#CGFloat x2#>, <#CGFloat y2#>, <#CGFloat radius#>)
//    self.maskView.layer.masksToBounds= YES;        //防止截图被截掉
    
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
//    CGContextAddRect(ctx, self.maskView.frame);
    
//    CGContextAddEllipseInRect(ctx, CGRectMake(0, 0, size.width, size.height));
//    [color set];
//    CGContextFillPath(ctx);
    
    // 指点可用范围, 可用范围的适用范围是在指定之后,也就说在在指定剪切的范围之前绘制的东西不受影响
//    CGContextClip(ctx);
    CGFloat smallX = 2 * 0.5;
    CGFloat smallY = 2 * 0.5;
    CGFloat smallW = self.pickingFieldRect.size.width;
    CGFloat smallH = self.pickingFieldRect.size.height;
    CGContextAddEllipseInRect(ctx, CGRectMake(smallX, smallY, smallW, smallH));
    CGContextClip(ctx);
    [self.originImage drawInRect:CGRectMake(smallX, smallY, smallW, smallH)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
//    [self.view.layer renderInContext:ctx];
//    
//    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - SavePhotosAblum Delegate
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSString *message;
    NSString *title;
    if (!error){
        title = nil;
        message = NSLocalizedString(@"订单已经保存到相册", @"");
    } else {
        title = @"存取相册失败";
        message = @"请在 设置-隐私-照片中，打开的访问权限";
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"知道了"
                                          otherButtonTitles:nil];
    [alert show];
    self.navigationItem.rightBarButtonItem.enabled = YES;
}
@end
